from PySide6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QTabWidget,
                               QWidget, QLabel, QPushButton, QTextEdit, QScrollArea,
                               QGridLayout, QFrame, QProgressBar, QTableWidget,
                               QTableWidgetItem, QHeaderView, QAbstractItemView,
                               QSystemTrayIcon, QMenu, QMessageBox, QFileDialog,
                               QApplication)
from PySide6.QtCore import Qt, QTimer, QThread, Signal, QPropertyAnimation, QEasingCurve, QRect
from PySide6.QtGui import QFont, QPainter, QColor, QBrush, QPen, QMovie
from ui_components import GlassFrame, StatItem
from data_analysis import DataAnalyzer
import json
import time
import os


class LoadingOverlay(QWidget):
    """加载中遮罩层"""

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents, False)
        self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground, True)
        self.setStyleSheet("background: transparent;")

        # 动画相关
        self.rotation_angle = 0
        self.animation_timer = QTimer()
        self.animation_timer.timeout.connect(self.rotate)

        # 设置布局
        layout = QVBoxLayout(self)
        layout.setAlignment(Qt.AlignmentFlag.AlignCenter)

        # 加载文本
        self.loading_label = QLabel("正在加载数据...")
        self.loading_label.setFont(QFont("Microsoft YaHei", 16, QFont.Weight.Bold))
        self.loading_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.loading_label.setStyleSheet("""
            QLabel {
                color: white;
                background: rgba(0, 0, 0, 0.7);
                border-radius: 10px;
                padding: 20px 40px;
                margin: 20px;
            }
        """)

        layout.addWidget(self.loading_label)

        # 进度提示
        self.progress_label = QLabel("初始化数据分析模块...")
        self.progress_label.setFont(QFont("Microsoft YaHei", 12))
        self.progress_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.progress_label.setStyleSheet("""
            QLabel {
                color: white;
                background: rgba(0, 0, 0, 0.5);
                border-radius: 8px;
                padding: 10px 20px;
                margin: 10px;
            }
        """)

        layout.addWidget(self.progress_label)

    def show_loading(self, message="正在加载数据..."):
        """显示加载遮罩"""
        self.loading_label.setText(message)
        self.progress_label.setText("正在初始化...")
        self.show()
        self.raise_()

        # 开始旋转动画
        self.animation_timer.start(50)  # 每50ms更新一次

    def hide_loading(self):
        """隐藏加载遮罩"""
        self.animation_timer.stop()
        self.hide()

    def update_progress(self, message):
        """更新进度信息"""
        self.progress_label.setText(message)
        QApplication.instance().processEvents()  # 强制更新UI（使用现代方式）

    def rotate(self):
        """旋转动画"""
        self.rotation_angle = (self.rotation_angle + 10) % 360
        self.update()

    def paintEvent(self, event):
        """绘制加载动画"""
        painter = QPainter(self)
        painter.setRenderHint(QPainter.RenderHint.Antialiasing)

        # 绘制半透明背景
        painter.fillRect(self.rect(), QColor(0, 0, 0, 120))

        # 绘制旋转的加载圆环
        center = self.rect().center()
        radius = 30

        painter.setPen(QPen(QColor(255, 255, 255, 200), 4))
        painter.translate(center.x(), center.y() - 60)
        painter.rotate(self.rotation_angle)

        # 绘制圆弧
        for i in range(8):
            alpha = 255 - (i * 30)
            painter.setPen(QPen(QColor(255, 255, 255, max(alpha, 50)), 4))
            painter.drawLine(0, -radius, 0, -radius + 10)
            painter.rotate(45)

        super().paintEvent(event)

    def resizeEvent(self, event):
        """窗口大小改变时调整遮罩大小"""
        if self.parent():
            self.setGeometry(self.parent().rect())
        super().resizeEvent(event)


class DataUpdateThread(QThread):
    """数据更新线程"""
    data_updated = Signal(dict, list, dict)
    progress_updated = Signal(str)
    error_occurred = Signal(str)

    def __init__(self, work_monitor, network_monitor):
        super().__init__()
        self.work_monitor = work_monitor
        self.network_monitor = network_monitor
        self.running = False
        self.first_run = True

    def run(self):
        """运行数据更新循环"""
        self.running = True
        self.network_monitor.start()

        try:
            while self.running:
                if self.first_run:
                    self.progress_updated.emit("正在获取工作数据...")
                    QThread.msleep(500)  # 模拟加载时间

                # 获取工作数据
                work_data = self.work_monitor.get_data()

                if self.first_run:
                    self.progress_updated.emit("正在获取网络连接...")
                    QThread.msleep(300)

                # 获取网络数据
                network_connections = self.network_monitor.get_connections()
                network_stats = self.network_monitor.get_statistics()

                # 如果没有真实的网络连接数据，创建示例数据
                if not network_connections:
                    if self.first_run:
                        self.progress_updated.emit("正在生成示例网络数据...")
                        QThread.msleep(200)
                    network_connections = self.create_sample_connections()
                    network_stats = {
                        'total_connections': len(network_connections),
                        'unique_ips': len(network_connections),
                        'countries': ['中国', '美国', '日本', '英国'],
                        'country_stats': {'中国': 2, '美国': 1, '日本': 1, '英国': 1}
                    }

                if self.first_run:
                    self.progress_updated.emit("正在分析数据...")
                    QThread.msleep(400)

                # 发送数据更新信号
                self.data_updated.emit(work_data, network_connections, network_stats)

                if self.first_run:
                    self.progress_updated.emit("数据加载完成！")
                    QThread.msleep(200)
                    self.first_run = False

                # 等待5秒后进行下一次更新
                for i in range(50):  # 分成50个100ms的片段，便于快速响应停止信号
                    if not self.running:
                        break
                    QThread.msleep(100)

        except Exception as e:
            self.error_occurred.emit(f"数据更新出错: {str(e)}")

    def stop(self):
        """停止数据更新"""
        self.running = False

        self.network_monitor.stop()

    def create_sample_connections(self):
        """创建示例连接数据"""
        sample_connections = []
        return sample_connections


class AnalysisDialog(QDialog):
    """数据分析对话框"""

    def __init__(self, work_monitor, network_monitor, parent=None):
        super().__init__(parent)
        self.work_monitor = work_monitor
        self.network_monitor = network_monitor

        # 初始化数据分析器 - 确保属性名称正确
        try:
            self.data_analyzer = DataAnalyzer()
            print("数据分析器初始化成功")
        except Exception as e:
            print(f"数据分析器初始化失败: {e}")
            self.data_analyzer = None

        # 数据更新线程
        self.data_thread = None
        self.is_data_loaded = False

        self.setWindowTitle("多模态数据分析")
        self.setGeometry(100, 100, 1200, 800)
        self.setModal(False)  # 非模态对话框

        self.setup_ui()

        # 创建加载遮罩
        self.loading_overlay = LoadingOverlay(self)
        self.loading_overlay.hide()

    def setup_ui(self):
        """设置用户界面"""
        layout = QVBoxLayout(self)
        layout.setSpacing(10)
        layout.setContentsMargins(15, 15, 15, 15)

        # 标题
        title_label = QLabel("🔍 多模态数据分析中心")
        title_label.setFont(QFont("Microsoft YaHei", 18, QFont.Weight.Bold))
        title_label.setStyleSheet("color: #2c3e50; margin-bottom: 10px;")
        layout.addWidget(title_label)

        # 创建标签页
        self.tab_widget = QTabWidget()
        self.tab_widget.setStyleSheet("""
            QTabWidget::pane {
                border: 2px solid #bdc3c7;
                border-radius: 8px;
                background: white;
            }
            QTabBar::tab {
                background: #ecf0f1;
                padding: 10px 20px;
                margin-right: 2px;
                border-top-left-radius: 8px;
                border-top-right-radius: 8px;
                font-weight: bold;
            }
            QTabBar::tab:selected {
                background: #3498db;
                color: white;
            }
        """)

        # 概览分析标签页
        self.create_overview_tab()

        # 效率分析标签页
        self.create_productivity_tab()

        # 网络监控标签页
        self.create_network_tab()

        layout.addWidget(self.tab_widget)

        # 底部按钮
        button_layout = QHBoxLayout()

        export_btn = QPushButton("📊 导出CSV数据")
        export_btn.clicked.connect(self.export_csv_data)
        export_btn.setStyleSheet("""
            QPushButton {
                background: #27ae60;
                color: white;
                padding: 8px 16px;
                border: none;
                border-radius: 6px;
                font-weight: bold;
            }
            QPushButton:hover {
                background: #2ecc71;
            }
        """)

        refresh_btn = QPushButton("🔄 刷新数据")
        refresh_btn.clicked.connect(self.refresh_all_data)
        refresh_btn.setStyleSheet("""
            QPushButton {
                background: #3498db;
                color: white;
                padding: 8px 16px;
                border: none;
                border-radius: 6px;
                font-weight: bold;
            }
            QPushButton:hover {
                background: #5dade2;
            }
        """)

        close_btn = QPushButton("❌ 关闭")
        close_btn.clicked.connect(self.close)
        close_btn.setStyleSheet("""
            QPushButton {
                background: #e74c3c;
                color: white;
                padding: 8px 16px;
                border: none;
                border-radius: 6px;
                font-weight: bold;
            }
            QPushButton:hover {
                background: #c0392b;
            }
        """)

        button_layout.addWidget(export_btn)
        button_layout.addWidget(refresh_btn)
        button_layout.addStretch()
        button_layout.addWidget(close_btn)

        layout.addLayout(button_layout)

    def create_overview_tab(self):
        """创建概览分析标签页"""
        overview_widget = QWidget()
        layout = QVBoxLayout(overview_widget)

        # 概览统计
        stats_frame = GlassFrame()
        stats_layout = QGridLayout(stats_frame)

        self.overview_stats = {}
        stats_labels = [
            ("总按键数", "keystrokes"),
            ("鼠标距离", "mouse_distance"),
            ("工作时长", "work_time"),
            ("活跃应用", "active_apps"),
            ("网络连接", "network_connections"),
            ("生产力指数", "productivity")
        ]

        for i, (label, key) in enumerate(stats_labels):
            stat_item = StatItem("--", label)
            self.overview_stats[key] = stat_item
            stats_layout.addWidget(stat_item, i // 3, i % 3)

        layout.addWidget(stats_frame)

        # 详细信息文本
        self.overview_text = QTextEdit()
        self.overview_text.setReadOnly(True)
        self.overview_text.setMaximumHeight(200)
        self.overview_text.setStyleSheet("""
            QTextEdit {
                background: white;
                border: 2px solid #bdc3c7;
                border-radius: 8px;
                padding: 10px;
                font-family: 'Microsoft YaHei';
            }
        """)
        self.overview_text.setPlainText("请等待数据加载...")
        layout.addWidget(self.overview_text)

        self.tab_widget.addTab(overview_widget, "📈 概览分析")

    def create_productivity_tab(self):
        """创建效率分析标签页"""
        productivity_widget = QWidget()
        layout = QVBoxLayout(productivity_widget)

        # 效率指标
        efficiency_frame = GlassFrame()
        efficiency_layout = QGridLayout(efficiency_frame)

        self.productivity_stats = {}
        productivity_labels = [
            ("专注度", "focus_level"),
            ("按键效率", "key_efficiency"),
            ("应用切换", "app_switches"),
            ("工作节奏", "work_rhythm")
        ]

        for i, (label, key) in enumerate(productivity_labels):
            stat_item = StatItem("--", label)
            self.productivity_stats[key] = stat_item
            efficiency_layout.addWidget(stat_item, i // 2, i % 2)

        layout.addWidget(efficiency_frame)

        # 应用使用排行
        app_frame = GlassFrame()
        app_layout = QVBoxLayout(app_frame)

        app_title = QLabel("📱 应用使用排行")
        app_title.setFont(QFont("Microsoft YaHei", 14, QFont.Weight.Bold))
        app_layout.addWidget(app_title)

        self.app_table = QTableWidget()
        self.app_table.setColumnCount(3)
        self.app_table.setHorizontalHeaderLabels(["应用名称", "使用时长", "使用频率"])
        self.app_table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
        self.app_table.setStyleSheet("""
            QTableWidget {
                background: white;
                border: 1px solid #bdc3c7;
                border-radius: 6px;
            }
            QHeaderView::section {
                background: #3498db;
                color: white;
                padding: 8px;
                font-weight: bold;
            }
        """)

        # 添加占位符
        self.app_table.setRowCount(1)
        placeholder_item = QTableWidgetItem("数据加载中...")
        placeholder_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
        self.app_table.setItem(0, 1, placeholder_item)
        self.app_table.setSpan(0, 0, 1, 3)

        app_layout.addWidget(self.app_table)

        layout.addWidget(app_frame)

        self.tab_widget.addTab(productivity_widget, "⚡ 效率分析")

    def create_network_tab(self):
        """创建网络监控标签页"""
        network_widget = QWidget()
        layout = QVBoxLayout(network_widget)

        # 网络统计
        network_stats_frame = GlassFrame()
        network_stats_layout = QGridLayout(network_stats_frame)

        self.network_stats = {}
        network_labels = [
            ("活跃连接", "active_connections"),
            ("唯一IP", "unique_ips"),
            ("国家数量", "countries"),
            ("总流量", "total_traffic")
        ]

        for i, (label, key) in enumerate(network_labels):
            stat_item = StatItem("--", label)
            self.network_stats[key] = stat_item
            network_stats_layout.addWidget(stat_item, 0, i)

        layout.addWidget(network_stats_frame)

        # 连接列表
        connections_frame = GlassFrame()
        connections_layout = QVBoxLayout(connections_frame)

        connections_title = QLabel("🌐 网络连接详情")
        connections_title.setFont(QFont("Microsoft YaHei", 14, QFont.Weight.Bold))
        connections_layout.addWidget(connections_title)

        self.connections_table = QTableWidget()
        self.connections_table.setColumnCount(6)
        self.connections_table.setHorizontalHeaderLabels(["远程IP", "端口", "国家/城市", "进程", "状态", "时间"])
        self.connections_table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
        self.connections_table.setStyleSheet("""
            QTableWidget {
                background: white;
                border: 1px solid #bdc3c7;
                border-radius: 6px;
            }
            QHeaderView::section {
                background: #e74c3c;
                color: white;
                padding: 8px;
                font-weight: bold;
            }
        """)

        # 添加占位符
        self.connections_table.setRowCount(1)
        placeholder_item = QTableWidgetItem("数据加载中...")
        placeholder_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
        self.connections_table.setItem(0, 2, placeholder_item)
        self.connections_table.setSpan(0, 0, 1, 6)

        connections_layout.addWidget(self.connections_table)

        layout.addWidget(connections_frame)

        self.tab_widget.addTab(network_widget, "🌐 网络监控")

    def showEvent(self, event):
        """对话框显示时启动数据加载"""
        super().showEvent(event)

        if not self.is_data_loaded:
            self.start_data_loading()

    def start_data_loading(self):
        """启动数据加载"""
        # 检查数据分析器是否可用
        if self.data_analyzer is None:
            try:
                self.data_analyzer = DataAnalyzer()
                print("重新初始化数据分析器成功")
            except Exception as e:
                print(f"重新初始化数据分析器失败: {e}")
                self.on_error_occurred(f"数据分析器初始化失败: {str(e)}")
                return

        # 调整加载遮罩大小
        self.loading_overlay.setGeometry(self.rect())

        # 显示加载遮罩
        self.loading_overlay.show_loading("正在启动数据分析...")

        # 创建并启动数据更新线程
        self.data_thread = DataUpdateThread(self.work_monitor, self.network_monitor)
        self.data_thread.data_updated.connect(self.on_data_updated)
        self.data_thread.progress_updated.connect(self.loading_overlay.update_progress)
        self.data_thread.error_occurred.connect(self.on_error_occurred)

        # 延迟启动线程，让UI有时间显示加载动画
        QTimer.singleShot(100, self.data_thread.start)

    def on_data_updated(self, work_data, network_connections, network_stats):
        """处理数据更新信号"""
        try:
            # 第一次加载完成，隐藏加载遮罩
            if not self.is_data_loaded:
                QTimer.singleShot(500, self.loading_overlay.hide_loading)  # 延迟隐藏，让用户看到完成状态
                self.is_data_loaded = True

            # 保存数据到数据库 - 确保数据分析器可用
            if self.data_analyzer is not None:
                try:
                    self.data_analyzer.save_work_data(work_data)
                    if network_connections:
                        self.data_analyzer.save_network_data(network_connections)
                except Exception as e:
                    print(f"保存数据时出错: {e}")

            # 更新各个标签页
            self.update_overview_tab(work_data, network_stats)
            self.update_productivity_tab(work_data)
            self.update_network_tab(network_connections, network_stats)

        except Exception as e:
            print(f"更新数据时出错: {e}")
            self.on_error_occurred(f"数据更新失败: {str(e)}")

    def on_error_occurred(self, error_message):
        """处理错误"""
        print(f"数据分析错误: {error_message}")
        self.loading_overlay.hide_loading()

        # 显示错误信息
        QMessageBox.warning(self, "数据加载错误", error_message)

    def update_overview_tab(self, work_data, network_stats):
        """更新概览标签页"""
        try:
            # 更新统计数据
            self.overview_stats["keystrokes"].value_label.setText(f"{work_data['keystrokes']:,}")
            self.overview_stats["mouse_distance"].value_label.setText(f"{work_data['mouse_distance']:.1f}px")

            # 格式化工作时长
            work_hours = int(work_data['total_work_time'] // 3600)
            work_minutes = int((work_data['total_work_time'] % 3600) // 60)
            self.overview_stats["work_time"].value_label.setText(f"{work_hours:02d}:{work_minutes:02d}")

            self.overview_stats["active_apps"].value_label.setText(str(len(work_data['applications'])))
            self.overview_stats["network_connections"].value_label.setText(str(network_stats['total_connections']))

            # 计算生产力指数 - 使用安全的方式
            if self.data_analyzer is not None:
                try:
                    productivity = self.data_analyzer.calculate_productivity_score(work_data)
                except Exception as e:
                    print(f"计算生产力指数时出错: {e}")
                    productivity = 0
            else:
                # 简单的生产力计算
                work_time_hours = work_data['total_work_time'] / 3600
                if work_time_hours > 0:
                    keyboard_activity = min(work_data['keystrokes'] / 1000, 1)
                    mouse_activity = min(work_data['mouse_distance'] * 0.0264583 / 1000, 1)
                    productivity = int((keyboard_activity + mouse_activity) * 50)
                else:
                    productivity = 0

            self.overview_stats["productivity"].value_label.setText(f"{productivity}%")

            # 更新详细信息
            current_app = work_data.get('current_app', '未知')
            self.overview_text.setPlainText(f"""
📊 当前工作状态分析：

🖥️  当前活跃应用: {current_app}
⌨️  平均按键速度: {work_data['keystrokes'] / max(work_data['total_work_time'] / 60, 1):.1f} 次/分钟
🖱️  鼠标活跃度: {work_data['mouse_distance'] / max(work_data['total_work_time'] / 60, 1):.1f} 像素/分钟
🌐  网络活跃度: {len([c for c in self.network_monitor.get_connections() if c.get('status') == 'ESTABLISHED'])} 个活跃连接
🎯  工作效率评级: {'优秀' if productivity >= 80 else '良好' if productivity >= 60 else '一般' if productivity >= 40 else '需要改进'}

💡 建议: {'继续保持当前工作状态' if productivity >= 70 else '可以适当增加工作强度' if productivity >= 50 else '建议休息片刻或调整工作方式'}
            """)
        except Exception as e:
            print(f"更新概览标签页时出错: {e}")

    def update_productivity_tab(self, work_data):
        """更新效率分析标签页"""
        try:
            work_time = max(work_data['total_work_time'], 1)

            # 计算各项效率指标
            focus_level = min(100, int(work_data['keystrokes'] / (work_time / 60) * 0.5))
            key_efficiency = min(100, int(work_data['keystrokes'] / max(work_time / 3600, 1) / 10))
            app_switches = len(work_data['applications'])
            work_rhythm = min(100, int(work_data['mouse_distance'] / (work_time / 60) * 0.01))

            self.productivity_stats["focus_level"].value_label.setText(f"{focus_level}%")
            self.productivity_stats["key_efficiency"].value_label.setText(f"{key_efficiency}%")
            self.productivity_stats["app_switches"].value_label.setText(f"{app_switches}")
            self.productivity_stats["work_rhythm"].value_label.setText(f"{work_rhythm}%")

            # 更新应用使用表格
            apps = list(work_data['applications'].values())
            apps.sort(key=lambda x: x['total_time'], reverse=True)

            self.app_table.setRowCount(min(len(apps), 10))  # 限制显示数量
            for i, app in enumerate(apps[:10]):
                # 应用名称
                self.app_table.setItem(i, 0, QTableWidgetItem(app['name']))

                # 使用时长
                hours = int(app['total_time'] // 3600)
                minutes = int((app['total_time'] % 3600) // 60)
                time_str = f"{hours:02d}:{minutes:02d}"
                self.app_table.setItem(i, 1, QTableWidgetItem(time_str))

                # 使用频率
                frequency = app.get('sessions', 0)
                self.app_table.setItem(i, 2, QTableWidgetItem(f"{frequency} 次"))

            # 如果没有应用数据，显示提示
            if not apps:
                self.app_table.setRowCount(1)
                no_data_item = QTableWidgetItem("暂无应用数据")
                no_data_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
                self.app_table.setItem(0, 1, no_data_item)
                self.app_table.setSpan(0, 0, 1, 3)

        except Exception as e:
            print(f"更新效率分析标签页时出错: {e}")

    def update_network_tab(self, connections, stats):
        """更新网络监控标签页"""
        try:
            # 更新网络统计
            self.network_stats["active_connections"].value_label.setText(str(stats['total_connections']))
            self.network_stats["unique_ips"].value_label.setText(str(stats['unique_ips']))
            self.network_stats["countries"].value_label.setText(str(len(stats['countries'])))

            # 计算总流量（模拟）
            total_mb = sum(hash(conn['remote_ip']) % 1000 for conn in connections) / 100
            self.network_stats["total_traffic"].value_label.setText(f"{total_mb:.1f}MB")

            # 更新连接表格 - 限制显示数量
            display_connections = connections[:20]
            self.connections_table.setRowCount(len(display_connections))
            for i, conn in enumerate(display_connections):
                self.connections_table.setItem(i, 0, QTableWidgetItem(conn['remote_ip']))
                self.connections_table.setItem(i, 1, QTableWidgetItem(str(conn['remote_port'])))

                location = f"{conn.get('country', '未知')}/{conn.get('city', '未知')}"
                self.connections_table.setItem(i, 2, QTableWidgetItem(location))

                self.connections_table.setItem(i, 3, QTableWidgetItem(conn.get('process_name', '未知')))
                self.connections_table.setItem(i, 4, QTableWidgetItem(conn.get('status', '未知')))

                import datetime
                time_str = datetime.datetime.fromtimestamp(conn['timestamp']).strftime("%H:%M:%S")
                self.connections_table.setItem(i, 5, QTableWidgetItem(time_str))

            # 如果没有连接数据，显示提示
            if not display_connections:
                self.connections_table.setRowCount(1)
                no_data_item = QTableWidgetItem("暂无网络连接数据")
                no_data_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
                self.connections_table.setItem(0, 2, no_data_item)
                self.connections_table.setSpan(0, 0, 1, 6)

        except Exception as e:
            print(f"更新网络监控标签页时出错: {e}")

    def refresh_all_data(self):
        """手动刷新所有数据"""
        if self.data_thread and self.data_thread.isRunning():
            # 如果线程正在运行，显示提示
            self.loading_overlay.show_loading("正在刷新数据...")
            self.loading_overlay.update_progress("重新获取最新数据...")

            # 延迟隐藏加载提示
            QTimer.singleShot(1000, self.loading_overlay.hide_loading)
        else:
            # 如果线程没有运行，重新启动
            self.is_data_loaded = False
            self.start_data_loading()

    def export_csv_data(self):
        """导出CSV数据"""
        try:
            # 检查数据分析器是否可用
            if self.data_analyzer is None:
                QMessageBox.warning(self, "导出失败", "数据分析器未初始化，无法导出数据。")
                return

            # 选择保存目录
            save_dir = QFileDialog.getExistingDirectory(
                self,
                "选择导出目录",
                os.path.expanduser("~/Desktop")
            )

            if save_dir:
                # 显示导出进度
                self.loading_overlay.show_loading("正在导出数据...")
                self.loading_overlay.update_progress("准备导出文件...")

                # 调用数据分析器的导出功能
                result_files = self.data_analyzer.export_data('csv', days=30, save_dir=save_dir)

                self.loading_overlay.hide_loading()

                if result_files:
                    file_list = "\n".join([f"• {os.path.basename(f)}" for f in result_files])
                    QMessageBox.information(
                        self,
                        "导出成功",
                        f"CSV数据已成功导出到：\n{save_dir}\n\n导出的文件：\n{file_list}"
                    )
                else:
                    QMessageBox.warning(self, "导出失败", "导出数据时发生错误，请检查数据库是否有数据。")

        except Exception as e:
            self.loading_overlay.hide_loading()
            QMessageBox.critical(self, "导出错误", f"导出失败：{str(e)}")

    def resizeEvent(self, event):
        """窗口大小改变时调整加载遮罩大小"""
        super().resizeEvent(event)
        if hasattr(self, 'loading_overlay'):
            self.loading_overlay.setGeometry(self.rect())

    def closeEvent(self, event):
        """关闭事件 - 停止所有数据更新并释放资源"""
        try:
            print("正在关闭数据分析对话框...")

            # 隐藏加载遮罩
            if hasattr(self, 'loading_overlay'):
                self.loading_overlay.hide_loading()

            # 停止数据更新线程
            if hasattr(self, 'data_thread') and self.data_thread:
                if self.data_thread.isRunning():
                    print("正在停止数据更新线程...")
                    self.data_thread.stop()

                    # 等待线程结束，设置超时避免卡死
                    if not self.data_thread.wait(2000):  # 等待2秒
                        print("强制终止数据更新线程...")
                        self.data_thread.terminate()
                        self.data_thread.wait(1000)  # 再等待1秒确保终止

                # 清理线程对象
                self.data_thread.deleteLater()
                self.data_thread = None

            # 重置数据加载状态
            self.is_data_loaded = False

            # 清理数据分析器资源
            if hasattr(self, 'data_analyzer') and self.data_analyzer is not None:
                try:
                    # 如果数据分析器有清理方法，调用它
                    if hasattr(self.data_analyzer, 'close'):
                        self.data_analyzer.close()
                except Exception as e:
                    print(f"清理数据分析器时出错: {e}")
                finally:
                    self.data_analyzer = None

            print("数据分析对话框已安全关闭，资源已释放")
            event.accept()

        except Exception as e:
            print(f"关闭对话框时出错: {e}")
            event.accept()
